package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.base.BaseTableListAdapter;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.RProInvoiceRecd;
import com.isunland.managesystem.entity.RProInvoiceRecdSub;
import com.isunland.managesystem.entity.ReceiptDetailLab;
import com.isunland.managesystem.entity.ReceiptDetailOriginal;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.SharedPreferencesUtil;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import org.json.JSONException;

/**
 * 开票明细列表页面.
 */
public class ReceiptDetailListFragment extends BaseListFragment {

  public static final String EXTRA_RECEIPT = "com.isunland.managesystem.ui.EXTRA_RECEIPT";
  protected static final int ADD = 1;// 添加
  protected static final int EDIT = 2;// 修改
  protected static final int WAIT_CHECK = 3;// 审核中
  protected static final int CHECK_PASS = 4;// 已审核
  private static final int REQUEST_DETAIL = 0;
  protected RProInvoiceRecd mReceiptDetail;
  protected int mMenuType;
  //    private ReceiptDetailAdapter mAdapter;
  private BaseTableListAdapter mAdapter;
  //    private List<AttendanceDetail> mAttendanceDetail;
  //    private boolean isFirst;
  //    private Callbacks mCallbacks;

  public static ReceiptDetailListFragment newInstance(RProInvoiceRecd receptDetail) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_RECEIPT, receptDetail);
    ReceiptDetailListFragment fragment = new ReceiptDetailListFragment();
    fragment.setArguments(args);
    return fragment;
  }

  //    @Override
  //    public void onAttach(Activity activity) {
  //        super.onAttach(activity);
  //        mCallbacks = (Callbacks) activity;
  //    }

  //    @Override
  //    public void onDetach() {
  //        super.onDetach();
  //        mCallbacks = null;
  //    }

  @Override public String getUrl() {
    return ApiConst.URL_RECEIPT_DETAIL_LIST_DATEBASE;
  }

  // volleyPost默认实现是从数据库获取内容.当新建时.数据库没有内容,会报错.
  // 禁用volleypost.要同时禁用进入页面和下拉刷新两处.
  @Override protected void isPostStart(boolean isPostStart, boolean isShowEmpty) {
    if (mMenuType == ADD) {
      super.isPostStart(false, true);
    } else {
      super.isPostStart(true, false);
    }
  }

  // 添加的时候禁用下拉刷新.
  @Override protected boolean isForbiddenRefresh() {
    return mMenuType == ADD;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    ((BaseVolleyActivity) getActivity()).getSupportActionBar().setTitle(R.string.goods_detail);
    ReceiptDetailLab.get(getActivity()).removeAll();// 每次创建子表页面的时候清空上次保存的数据.

    ReceiptDetailLab.get(getActivity()).setUnsaved(false);
    mReceiptDetail = (RProInvoiceRecd) getArguments().getSerializable(EXTRA_RECEIPT);
    if (mReceiptDetail == null) {
      // 添加
      mMenuType = ADD;
    } else {
      // 其他
      String dataStattus = mReceiptDetail.getDataStatus();
      if (dataStattus.equals(DataStatus.WAIT_CHECK)) {
        mMenuType = WAIT_CHECK;
      }
      if (dataStattus.equals(DataStatus.CHECK_PASS)) {
        mMenuType = CHECK_PASS;
      }
      if (dataStattus.equals(DataStatus.CHECK_PASS)) {
        mMenuType = CHECK_PASS;
      }
      if (dataStattus.equals(DataStatus.ABORT) || dataStattus.equals(DataStatus.NEW)) {
        mMenuType = EDIT;
      }
    }
    super.onCreate(savedInstanceState);
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<String, String>();

    params.put("mainId", mReceiptDetail.getId());

    params.put("memberCode", CurrentUser.newInstance(getActivity()).getMemberCode());

    return params;
  }

  @Override public void resolveResponse(String arg0) {

    List<RProInvoiceRecdSub> rows;
    try {
      ReceiptDetailOriginal original = new Gson().fromJson(arg0, ReceiptDetailOriginal.class);

      rows = original.getRows();
    } catch (JsonSyntaxException e) {
      // Auto-generated catch block
      e.printStackTrace();

      rows = new ReceiptDetailOriginal().getRows();
    }
    // 联网后更新单例数据.
    ReceiptDetailLab.get(getActivity()).removeAll();

    ReceiptDetailLab.get(getActivity()).addAll(rows);

    // 如果联网获取子表数据不为空,将未保存标记为true.
    // if (mList!=null&&mList.size()>0) {
    // ReceiptDetailLab.get(getActivity()).setUnsaved(true);
    // }
    setAdapter(ReceiptDetailLab.get(getActivity()).getList());
  }

  private void setAdapter(List<RProInvoiceRecdSub> detail) {
    if (detail == null) {
      detail = new ArrayList<RProInvoiceRecdSub>();
    }
    LinkedHashMap<String, String> map = new LinkedHashMap<>();
    map.put("货品名称", "materialName");
    map.put("数量", "mnumber");
    map.put("金额", "msumPrice");
    mAdapter = new BaseTableListAdapter(getActivity(), detail, map, new RProInvoiceRecdSub());
    setListAdapter(mAdapter);

    // mAdapter.notifyDataSetChanged();

  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    Intent i = new Intent(getActivity(), ReceiptDetailActicity.class);
    if (mReceiptDetail == null) {
      mReceiptDetail = new RProInvoiceRecd();
      mReceiptDetail.setDataStatus("new");
    }
    //        String receiptDetailId = detail.getItem(position - 1).getId();
    String receiptDetailId =
        ReceiptDetailLab.get(getActivity()).getList().get(position - 1).getId();
    i.putExtra(ReceiptDetailFragment.EXTRA_RECEIPT_DETAIL_ID, receiptDetailId);
    i.putExtra(ReceiptDetailFragment.EXTRA_DATA_STATUS, mReceiptDetail.getDataStatus());
    startActivityForResult(i, REQUEST_DETAIL);
    super.onListItemClick(l, v, position, id);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    //		inflater.inflate(R.menu.menu_save_detail, menu);
    //		menu.getItem(0).setTitle("保存开票明细");
    switch (mMenuType) {
      case ADD:
        inflater.inflate(R.menu.menu_save_detail, menu);
        break;
      case EDIT:
        inflater.inflate(R.menu.menu_save_detail, menu);
        break;

      default:
        super.onCreateOptionsMenu(menu, inflater);
        break;
    }
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        unSaveHint();
        return true;

      case R.id.menu_item_detail://获取明细
        if (mMenuType == WAIT_CHECK || mMenuType == CHECK_PASS) {
          ToastUtil.show("只有草稿或终止状态可以修改");
          return true;
        }

        // 主记录id,合同订单id,合同订单类型.用于动态生成子表.
        String id =
            SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.RECEIPT_ID, "");
        String contractId = SharedPreferencesUtil.getString(getActivity(),
            SharedPreferencesUtil.RECEIPT_CONTRACT_ID, "");
        String contractType = SharedPreferencesUtil.getString(getActivity(),
            SharedPreferencesUtil.RECEIPT_CONTRACT_TYPE, "");
        if (TextUtils.isEmpty(id)) {
          ToastUtil.show("无法获取主表id");
          return true;
        }
        if (TextUtils.isEmpty(contractId)) {
          ToastUtil.show(R.string.noContractSelected);
          return true;
        }
        if (TextUtils.isEmpty(contractType)) {
          ToastUtil.show("无法获取合同类型");
          return true;
        }
        contractId = MyUtils.getSingleQuotesString(contractId);
        volleyPostGenerate(id, contractId, contractType);
        return true;
      case R.id.menu_item_add://添加明细
        Intent i = new Intent(getActivity(), ReceiptDetailActicity.class);
        i.putExtra(ReceiptDetailFragment.EXTRA_DATA_STATUS, "new");
        startActivityForResult(i, REQUEST_DETAIL);
        return true;

      //                ToastUtil.show("添加");
      //                break;
      case R.id.menu_item_save:
        if (ReceiptDetailLab.get(getActivity()).getList().size() == 0) {
          ToastUtil.show("列表数据为空无法保存");
          return true;
        }

        volleyPostSave();
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
    //        return super.onOptionsItemSelected(item);
  }

  /**
   * 没有保存的提示,
   */
  protected void unSaveHint() {
    if (ReceiptDetailLab.get(getActivity()).isUnsaved()) {

      new AlertDialog.Builder(getActivity()).setTitle("提示")
          .setMessage("数据修改后没有保存,是否保存")
          .setPositiveButton("保存", new OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              volleyPostSave();
            }
          })
          .setNegativeButton("不保存", new OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {

              getActivity().finish();
            }
          })
          .create()
          .show();
    } else {
      if (NavUtils.getParentActivityName(getActivity()) != null) {
        NavUtils.navigateUpFromSameTask(getActivity());
      }
    }
  }

  private void volleyPostGenerate(String id, String contractId, String contractType) {
    MyUtils.showDialogLoading(getActivity());
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_RECEIPT_DETAIL_LIST_GENERATE);
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("recdId", id); // 对应的开票主记录的Id
    params.put("ids", contractId);// 合同或者订单的id（可以多选）
    params.put("memberCode", CurrentUser.newInstance(getActivity()).getMemberCode());// 会员编码
    params.put("contractOrderType", contractType);// 合同订单类型（contract，in，out）

    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        try {

          List<RProInvoiceRecdSub> rows;
          try {
            ReceiptDetailOriginal original = new Gson().fromJson(arg0, ReceiptDetailOriginal.class);

            rows = original.getRows();
          } catch (JsonSyntaxException e) {
            // Auto-generated catch block
            e.printStackTrace();

            rows = new ReceiptDetailOriginal().getRows();
          }
          // //获取明细执行后需要放在现有数据的后面,而不是清空,因为要看到原来的已经保存的数据.
          // ReceiptDetailLab.get(getActivity()).removeAll();

          ReceiptDetailLab.get(getActivity()).addAll(rows);

          // 如果联网获取子表数据不为空,将未保存标记为true.
          if (ReceiptDetailLab.get(getActivity()).getList().size() > 0) {
            ReceiptDetailLab.get(getActivity()).setUnsaved(true);
          }
          setAdapter(ReceiptDetailLab.get(getActivity()).getList());
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.getFailure);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        LogUtil.e("VolleyError", arg0);
        ToastUtil.show(R.string.getFailure);
      }
    });
  }

  private void volleyPostSave() {
    MyUtils.showDialogLoading(getActivity(), R.string.loadingSave);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_RECEIPT_DETAIL_SAVE);
    HashMap<String, String> params = new HashMap<String, String>();
    String json = new Gson().toJson(ReceiptDetailLab.get(getActivity()).getList());
    params.put("json", json);

    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        try {
          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          String successType = successsMessage.getResult();
          if (successType.equals("1")) {
            ReceiptDetailLab.get(getActivity()).setUnsaved(false);
            ToastUtil.show(R.string.save_success);
            // 保存成功后跳转到主表.
            turnToMain();
          } else {
            ToastUtil.show(R.string.save_failure);
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.save_failure);
        }
      }

      private void turnToMain() {
        Double salestax = 0.0;
        Double salesMoney = 0.0;
        Double sumMoney = 0.0;
        for (RProInvoiceRecdSub item : ReceiptDetailLab.get(getActivity()).getList()) {
          // 销项额
          // protected Double mtsumPrice;
          // 销项税
          // protected Double outputTax;
          salestax += item.getOutputTax();
          salesMoney += item.getMtsumPrice();
          // 价税合计
          sumMoney += item.getMsumPrice();
        }
        Intent data = new Intent();
        data.putExtra(ReceiptInfoFragment.EXTRA_SALES_MONEY, salesMoney);
        data.putExtra(ReceiptInfoFragment.EXTRA_SALES_TAX, salestax);
        data.putExtra(ReceiptInfoFragment.EXTRA_SUM_MONEY, sumMoney);
        getActivity().setResult(Activity.RESULT_OK, data);
        getActivity().finish();
        //                mCallbacks.onRefresh(salestax, salesMoney, sumMoney);

      }

      @Override public void onVolleyError(VolleyError arg0) {
        LogUtil.e("VolleyError", arg0);
        ToastUtil.show(R.string.save_failure);
      }
    });
  }

  public void refresh() {
    volleyPost();
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }

    if (requestCode == REQUEST_DETAIL) {

      setAdapter(ReceiptDetailLab.get(getActivity()).getList());
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  public interface Callbacks {
    void onRefresh(Double salestax, Double salesMoney, Double sumMoney);
  }
}
